package com.fw.system.web.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.system.web.model.entity.FwSku;
import com.fw.system.web.dao.FwSkuMapper;
import com.fw.system.web.service.IFwSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商品sku规格表 服务实现类
 * </p>
 *
 * @author 姚
 * @since 2021-05-10
 */
@Service
public class FwSkuServiceImpl extends ServiceImpl<FwSkuMapper, FwSku> implements IFwSkuService {

    /**
     * 获取剩余库存
     *
     * @param skuId 规格ID
     * @return 剩余库存
     * @Author 姚
     * @Date 2021/7/6
     **/
    @Override
    public Integer getBalance(String skuId) {
        FwSku sku = getById(skuId);
        if (sku == null){
            return 0;
        }
        return sku.getSkuBalance();
    }

    /**
     * 减库存
     *
     * @param skuId  guigeID
     * @param buyNum 购买数量
     * @return 是否减成功
     * @Author 姚
     * @Date 2021/7/6
     **/
    @Override
    public boolean subtractBalance(String skuId, Integer buyNum) {
        Integer balance = getBalance(skuId);
        if (balance < buyNum){
            return false;
        }

        return update(Wrappers.<FwSku>lambdaUpdate()
                .set(FwSku::getSkuBalance, balance - buyNum)
                .eq(FwSku::getId, skuId));
    }

    /**
     * 加库存（取消订单等）
     *
     * @param skuId  guigeID
     * @param buyNum 购买数量
     * @return 是否加成功
     * @Effect
     * @Author 姚
     * @Date 2021/7/7
     **/
    @Override
    public boolean addBalance(String skuId, Integer buyNum) {
        return update(Wrappers.<FwSku>lambdaUpdate()
                .set(FwSku::getSkuBalance, getBalance(skuId) - buyNum)
                .eq(FwSku::getId, skuId));
    }
}
